package test;

import java.io.*;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Pattern;

/**
 * Created by liute on 2016/8/7.
 */
public class TextSplit {
    public static void main(String[] args) throws IOException {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        Pattern pattern = Pattern.compile("^\\d{4}([-]\\d{2}){2} \\d{1,2}(:\\d{2}){2}");
        Calendar startDate = Calendar.getInstance();
        Calendar endDate = Calendar.getInstance();
        startDate.set(2014, 11, 4);
        endDate.set(2016, 0, 1);

        String currentFileName = simpleDateFormat.format(startDate.getTime());
        String fileSuffix = ".txt";

        BufferedReader bufferedReader = new BufferedReader(new FileReader("D:\\ideaworkspace\\liuteng\\src\\main\\resources\\4G.txt"));
        String outFolder = "D:\\ideaworkspace\\liuteng\\src\\main\\java\\test\\t2015";

        Map<String, String> files = new HashMap<String, String>();

        String s;
        while ((s = bufferedReader.readLine()) != null) {
            System.out.println(s);
            if (pattern.matcher(s).find()) {
                boolean flag = true;
                while (flag){
                    if (s.contains(currentFileName)) {
                        flag = false;
                        files.put(currentFileName, (files.get(currentFileName)==null?"":files.get(currentFileName)) + "\n" + s);
                    }else {
                        startDate.add(Calendar.DAY_OF_MONTH, 1);
                        currentFileName = simpleDateFormat.format(startDate.getTime());
                        files.put(currentFileName, "");
                    }
                }
            } else {
                files.put(currentFileName, (files.get(currentFileName)==null?"":files.get(currentFileName)) + "\n" + s);
            }
        }

        for (String s1 : files.keySet()) {
            BufferedWriter bw = new BufferedWriter(new FileWriter(outFolder + "\\" + s1 + fileSuffix));
            bw.write(files.get(s1));
            bw.flush();
        }
    }
}
